<?php
/**
 * 申请文件导出
 * User: dxk
 * Date: 2020/08/05
 */
namespace App\Service\Core\Admin\File;

use App\Model\Core\Admin\AdminFileModel;
use App\Service\Core\CoreBaseService;
use App\Traits\ModelStoreTrait;
use Illuminate\Foundation\Bus\DispatchesJobs;

class AdminExportFileApplyService extends CoreBaseService
{
    use DispatchesJobs;
    use ModelStoreTrait;

    /**
     * 设置搜索参数
     * @param string|array $request 搜索参数
     * @return $this
     */
    public function setRequest($request)
    {
        $request = json_encode($request);
        $this->setParam('request', $request);
        return $this;
    }

    /**
     * 设置导出备注
     * @param $remark
     * @return $this
     */
    public function setRemark($remark)
    {
        $remark = trim($remark);
        if (empty($remark)) {
            $this->setError('备注不能为空');
        }
        $this->setParam('remark', $remark);
        return $this;
    }

    /**
     * 设置导出类型
     * @param $export_type
     * @return $this
     */
    public function setExportType($export_type)
    {
        $export_type = (int)$export_type;
        if (!array_key_exists($export_type, AdminFileModel::$export_type)) {
            $this->setError('不支持的导出类型');
        }
        $this->setParam('export_type', $export_type);
        return $this;
    }

    /**
     * 设置事件名称
     * @param $handle
     * @return $this
     */
    public function setHandle($handle)
    {
        if (!is_string($handle) || !is_callable([new $handle(), 'asyncExport'])) {
            $this->setError('handle不可调用');
            return $this;
        }
        $this->setParam('handle', $handle);
        return $this;
    }

    /**
     * 请求下载
     * @return array
     */
    public function apply()
    {
        $this->check_required_param(['request', 'remark', 'export_type', 'handle']);
        if (!empty($this->errors)) {
            return alert_info(1, $this->errors[0], $this->errors);
        }
        $data = [
            'request' => $this->getParam('request'),
            'remark' => $this->getParam('remark'),
            'file_type' => $this->getParam('export_type'),
            'operate_type' => AdminFileModel::OPERATE_EXPORT,
            'handle' => $this->getParam('handle'),
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => $this->operate_by,
            'created_user_id' => $this->operate_id,
            'status' => AdminFileModel::STATUS_WAIT
        ];
        $file_id = AdminFileModel::getInstance()->addOne($data);
        if ($file_id === false) {
            return alert_info(1, '数据库插入异常');
        }
        (new AdminFileMonitorService())->pushToQueue($file_id);
        return alert_info(0, '文件正在导出,请到我的文件中查看进度', ['file_id' => $file_id]);
    }
}
